package com.gm.census.service.impl;

import java.util.List;

import com.gm.census.model.pojo.Congregation;
import com.gm.census.service.BaseService;
import com.gm.census.service.CongregationService;
import com.gm.census.service.PagedListResult;
import com.google.appengine.api.datastore.Cursor;
import com.googlecode.objectify.Key;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Query;

public class CongregationServiceImpl extends
		BaseServiceImpl<Congregation, Long> implements CongregationService {

	static {
		ObjectifyService.register(Congregation.class);
	}

	protected Key<String> parent() {
		return new Key<String>(String.class, "congregations");
	}

	@SuppressWarnings("unchecked")
	protected Key<Congregation> key(Long id){
		return new Key<Congregation>(parent(),Congregation.class,id);
	}
	
	@Override
	public Congregation find(final Long id) {
		return inNs(new DefaultNSCmd<Congregation>() {
			@Override
			public Congregation execute() {
				return begin().find(key(id));
			}
		});
	}

	@Override
	public Congregation put(final Congregation e) {
		return inNs(new DefaultNSCmd<Congregation>() {
			@Override
			public Congregation execute() {
				e.setParent(parent());
				Key<Congregation> k = begin().put(e);
				e.setId(k.getId());
				return e;
			}
		});
	}

	@Override
	public void delete(final Long e) {
		inNs(new DefaultNSCmd<Object>() {
			@Override
			public Object execute() {
				begin().delete(key(e));
				return e;
			}
		});
	}

	@Override
	public Congregation get(final Long id) {
		return inNs(new DefaultNSCmd<Congregation>() {
			@Override
			public Congregation execute() {
				return begin().get(key(id));
			}
		});
	}

	@Override
	public List<Congregation> list() {
		return inNs(new DefaultNSCmd<List<Congregation>>() {

			@Override
			public List<Congregation> execute() {
				return begin().query(Congregation.class).ancestor(parent())
						.limit(BaseService.DEFAULT_QUERY_PAGE).list();
			}

		});
	}

	@Override
	public PagedListResult<List<Congregation>> list(final String index,
			final Integer pageSize) {
		return inNs(new DefaultNSCmd<GAEPagedListResult<Congregation>>() {

			@Override
			public GAEPagedListResult<Congregation> execute() {
				Query<Congregation> q = begin().query(Congregation.class)
						.ancestor(parent());
				if (pageSize > 0)
					q.limit(pageSize);
				else
					q.limit(BaseService.DEFAULT_QUERY_PAGE);

				if (index != null && index.length() > 0) {
					Cursor cursor = Cursor.fromWebSafeString(index);
					q.startCursor(cursor);
				}

				return new GAEPagedListResult<Congregation>(q.iterator());
			}

		});
	}

	@Override
	public PagedListResult<List<Congregation>> list(String index) {
		return list(index, Integer.MAX_VALUE);
	}

}
